<template>
    <el-dialog
      v-model="visible"
      title="新增下一级设备"
      width="95%"
      top="5vh"
    >
      <!-- 可拖动列宽的表格 -->
      <el-table
        :data="rows"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f9fafb', fontWeight: 600 }"
        :resizable="true"
      >
        <el-table-column prop="parentName" label="上一级名称" min-width="160">
          <template #default="{ row }">
            <el-input v-model="row.parentName" placeholder="上一级名称" />
          </template>
        </el-table-column>
  
        <el-table-column prop="nodeType" label="类型" min-width="120">
          <template #default="{ row }">
            <el-select v-model="row.nodeType" >
              <!-- <el-option label="系统" value="SYSTEM" />
              <el-option label="母设备" value="MACHINE" /> -->
              <el-option label="子设备" value="MODULE" />
              <el-option label="部件" value="COMPONENT" />
              <el-option label="零件" value="PART" />
            </el-select>
          </template>
        </el-table-column>
  
        <el-table-column prop="code" label="编码" min-width="150">
          <template #default="{ row }">
            <el-input v-model="row.code" />
          </template>
        </el-table-column>
  
        <el-table-column prop="name" label="名称" min-width="150">
          <template #default="{ row }">
            <el-input v-model="row.name" placeholder="请输入名称" />
          </template>
        </el-table-column>
  
        <el-table-column prop="beType" label="类别" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.beType" />
          </template>
        </el-table-column>
  
        <el-table-column prop="mokuai" label="模块" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.mokuai" />
          </template>
        </el-table-column>
  
        <el-table-column prop="area" label="区域" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.area" />
          </template>
        </el-table-column>
  
        <el-table-column prop="specification" label="规格" min-width="150">
          <template #default="{ row }">
            <el-input v-model="row.specification" />
          </template>
        </el-table-column>
  
        <el-table-column prop="material" label="材质" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.material" />
          </template>
        </el-table-column>
  
        <el-table-column prop="unit" label="单位" min-width="100">
          <template #default="{ row }">
            <el-input v-model="row.unit" />
          </template>
        </el-table-column>
  
        <el-table-column prop="quantity" label="数量" min-width="100">
          <template #default="{ row }">
            <el-input-number v-model="row.quantity" :min="0" />
          </template>
        </el-table-column>
  
        <el-table-column prop="amount" label="金额(万)" min-width="120">
          <template #default="{ row }">
            <el-input-number v-model="row.amount" :min="0" />
          </template>
        </el-table-column>
  
        <el-table-column prop="designTemp" label="设计温度(℃)" min-width="130">
          <template #default="{ row }">
            <el-input-number v-model="row.designTemp" />
          </template>
        </el-table-column>
  
        <el-table-column prop="designPress" label="设计压力(MPa)" min-width="130">
          <template #default="{ row }">
            <el-input-number v-model="row.designPress" />
          </template>
        </el-table-column>
  
        <el-table-column prop="motorPower" label="电机功率(KW)" min-width="130">
          <template #default="{ row }">
            <el-input-number v-model="row.motorPower" />
          </template>
        </el-table-column>
  
        <el-table-column prop="mixingType" label="搅拌形式" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.mixingType" />
          </template>
        </el-table-column>
  
        <el-table-column prop="brand" label="品牌" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.brand" />
          </template>
        </el-table-column>
  
        <el-table-column prop="manufacturer" label="厂家" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.manufacturer" />
          </template>
        </el-table-column>
  
        <el-table-column prop="remark" label="备注" min-width="180">
          <template #default="{ row }">
            <el-input v-model="row.remark" />
          </template>
        </el-table-column>
  
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ $index }">
            <el-button link type="primary" @click="copyRow($index)">复制</el-button>
            <el-button link type="danger" @click="removeRow($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 新增按钮 -->
      <div class="add-btn">
        <el-button type="success" plain size="small" @click="addRow">
          ＋ 新增一行
        </el-button>
      </div>
  
      <template #footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { reactive, ref } from "vue";
  import { ElMessage } from "element-plus";
  
  const emit = defineEmits(["confirm"]);
  
  const visible = ref(false);
  const rows = reactive([]);
  const parentInfo = ref({ type: "SYSTEM", name: "" });
  
  const ORDER = ["SYSTEM", "MACHINE", "MODULE", "COMPONENT", "PART"];
  
  function open(parentType, parentName) {
    visible.value = true;
    parentInfo.value = { type: parentType, name: parentName || "" };
    rows.splice(0);
    rows.push(makeEmptyRow());
  }
  
  function nextType(type) {
    const idx = ORDER.indexOf(type);
    return ORDER[idx + 1] || "PART";
  }
  
  function makeEmptyRow(customParentName, forcedType) {
    return {
      uid: Math.random().toString(36).slice(2),
      parentName: customParentName || parentInfo.value.name,
      nodeType: forcedType || nextType(parentInfo.value.type),
      code: "",
      name: "",
      beType: "",
      mokuai: "",
      area: "",
      specification: "",
      material: "",
      unit: "",
      quantity: 0,
      amount: 0,
      designTemp: 0,
      designPress: 0,
      motorPower: 0,
      mixingType: "",
      brand: "",
      manufacturer: "",
      remark: "",
    };
  }
  
  // ✅ 校验函数（新增/确定都会调用）
  function validateRows() {
    for (let i = 0; i < rows.length; i++) {
      const r = rows[i];
      if (!r.parentName || !r.name) {
        ElMessage.error(`第 ${i + 1} 行：上一级名称和名称不能为空`);
        return false;
      }
    }
    return true;
  }
  
  // ✅ 新增一行（带校验）
  function addRow() {
    if (!validateRows()) return; // ❌ 校验失败中断
    const last = rows[rows.length - 1];
    let next = last.nodeType === "PART" ? "PART" : nextType(last.nodeType);
    rows.push(makeEmptyRow(last.name || last.parentName || parentInfo.value.name, next));
  }
  
  // ✅ 删除一行
  function removeRow(i) {
    rows.splice(i, 1);
    if (!rows.length) addRow();
  }
  
  // ✅ 复制一行
  function copyRow(i) {
    const newRow = JSON.parse(JSON.stringify(rows[i]));
    newRow.uid = Math.random().toString(36).slice(2);
    rows.splice(i + 1, 0, newRow);
  }
  
  // ✅ 确认（带校验）
  function confirm() {
    if (!validateRows()) return;
    if (!rows.length) return ElMessage.warning("请至少添加一条记录");
    emit("confirm", JSON.parse(JSON.stringify(rows)));
    visible.value = false;
  }
  
  defineExpose({ open });
  </script>
  
  <style scoped>
  .add-btn {
    text-align: right;
    padding: 10px;
    background: #fafafa;
    border-top: 1px solid #ebeef5;
  }
  </style>
  